package day02;

import entity.Demo;
import utils.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

public class LoginDemo {
    public static void main(String[] args) {
        //1.
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入用户名：");
        String username = sc.nextLine();
        System.out.print("请输入密码：");
        String password = sc.nextLine();
        //2.方法1使用statement对象，存在sql注入隐患
        //Demo user = new LoginDemo().login1(username,password);
        //方法2使用preparedStatement，解决sql注入隐患
        Demo user = new LoginDemo().login2(username,password);
        //3.
        if (user == null){
            System.out.println("登录失败");
        }else {
            System.out.println(user.getDname() + "欢迎您");
        }
    }

    private Demo login2(String username, String password) {
        Connection con;
        PreparedStatement ps;
        ResultSet rs;
        try {
            con = JDBCUtils.getConnection();
            String sql = "select * from demo where dname = ? and dpwd = ?";
            ps = con.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            while (rs.next()){
                Demo d = new Demo(
                        rs.getInt(1),
                        rs.getString(2),
                        rs.getString(3));
                return d;
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con,ps,rs);
        return null;
    }

    private Demo login1(String username, String password) {
        Connection con;
        Statement sta;
        ResultSet rs;
        try {
            con = JDBCUtils.getConnection();
            sta = con.createStatement();
            String sql = "select * from demo where dname = '"+username+"' and dpwd = '"+password+"'";
            rs = sta.executeQuery(sql);
            while (rs.next()){
                Demo d = new Demo(
                        rs.getInt(1),
                        rs.getString(2),
                        rs.getString(3));
                return d;
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        JDBCUtils.close(con,sta,rs);
        return null;
    }
}
